package com.bank.utils;


import com.bank.domain.Bank;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author mtl
 * 2021/6/1
 */
public class BlogText {
    private static String indexUrl="http://www.chakahao.com/lhh/";


    public static List<Bank> Blog(Integer page){
            String url="http://www.chakahao.com/lhh/index_"+page+".html";

            ArrayList<Bank> list = new ArrayList<>();
            Connection connection = Jsoup.connect(url);
            connection.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
            try {
                Document document = connection.timeout(100000).get();
                Elements elements = document.getElementsByClass("content").first().children();
                Elements byClass = elements.get(0).getElementsByClass("card-table");
                Element tbody = byClass.get(0).getElementsByTag("tbody").get(0);
                Elements trs = tbody.getElementsByTag("tr");

                trs.forEach(data->{
                    Bank bank = new Bank();
                    String name = data.getElementsByTag("td").get(1).html();
                    String number = data.getElementsByTag("td").get(2).getElementsByTag("a").after("title").text();
                    String href = data.getElementsByTag("td").get(2).getElementsByTag("a").attr("href");
                    bank.setName(name);
                    bank.setNumber(number);
                    //通过详情链接取电话号码
                    Connection connect = Jsoup.connect(indexUrl + href);
                    connect.header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36");
                    try {
                        Document details = connect.timeout(100000).get();
                        Elements elements1 = details.getElementsByClass("content").first().children();
                        Element markdown = elements1.get(0).getElementsByClass("markdown").get(0).getElementsByTag("div").get(2);
                        String p = markdown.getElementsByTag("p").get(1).getElementsByTag("strong").text();
                        bank.setPhone(p);
                        list.add(bank);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });

            } catch (IOException e) {
                e.printStackTrace();
            }
            return list;

    }

}
